package com.alex.httphack;

import org.apache.http.HttpVersion;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParamBean;

public class HackHttpClient extends DefaultHttpClient {

	private static HttpParams httpParams;

	private static SingleClientConnManager connectionManager;

	/**
	 * 最大连接数
	 */
	public final static int MAX_TOTAL_CONNECTIONS = 100;

	/**
	 * 每个路由最大连接数
	 */
	public final static int MAX_ROUTE_CONNECTIONS = 50;

	/**
	 * 连接超时时间
	 */
	public final static int CONNECT_TIMEOUT = 15000;

	/**
	 * 读取超时时间
	 */
	public final static int READ_TIMEOUT = 15000;

	static {
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));
		registry.register(new Scheme("https", 443, SSLSocketFactory
				.getSocketFactory()));

		connectionManager = new SingleClientConnManager(registry);
		// 设置最大连接数
		// connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
		// 设置每个路由最大连接数
		// connectionManager.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);

		httpParams = new BasicHttpParams();
		// 设置连接超时时间
		HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);
		// 设置读取超时时间
		HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);

		HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(httpParams);
		paramsBean.setVersion(HttpVersion.HTTP_1_1);
		paramsBean.setContentCharset("UTF-8");
		paramsBean.setUseExpectContinue(true);
		paramsBean
				.setUserAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13");

		httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	}

	public HackHttpClient() {
		super(connectionManager, httpParams);
		setHttpRequestRetryHandler(new HackRequestRetryHandler());
		addRequestInterceptor(new HackHttpRequestInterceptor());
	}

	public static void main(String[] args) {
		System.out.println(httpParams
				.getParameter(CoreProtocolPNames.PROTOCOL_VERSION));
		System.out.println(httpParams
				.getParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET));
		System.out.println(httpParams
				.getParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE));
		System.out.println(httpParams
				.getParameter(CoreProtocolPNames.USER_AGENT));
	}
}
